package com.itheima.service;

import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class MyDetailService implements UserDetailsService {

    //注入接口
    @Reference
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查询到对应的User对象,以及对应的属性:角色集合以及角色对应的权限集合
        User user=userService.findUserByUsername(username);

        //创建存储权限和角色的集合
        List<GrantedAuthority> list=new ArrayList<>();

        //遍历user的角色集合
        for (Role role : user.getRoles()) {

            //将角色的keyword添加到集合中
            list.add(new SimpleGrantedAuthority(role.getKeyword()));

            //遍历每个角色的权限集合
            for (Permission permission : role.getPermissions()) {

                //将权限的keyword添加到集合中
                list.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }

        //返回对象 构造器参数:参一:用户名,参二:密码,参三:权限和角色的单列集合
        return new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),list);
    }
}
